﻿using SuperX.Common.Helper;
using SuperX.Common.Log;
using SuperX.Helper.ServiceResponse;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.AspNetCore.Mvc.Filters;
using System;
using System.Linq;
using System.Net.Http;
using System.Text;

namespace SuperX.DataCenterService.WebAPI
{
    public class ApiResponseAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuted(ActionExecutedContext context)
        {
            if (context.Exception == null && context.Result != null)
            {
                // 返回结果为JsonResult的请求进行Result包装
                if (context.Result is ObjectResult)
                {
                    var result = context.Result as ObjectResult;
                    if (result.Value == null)
                        context.Result = new ObjectResult(ApiResponse<string>.Success("执行成功！"));
                    else if (result.Value.GetType().Namespace != "SuperX.Helper.ServiceResponse")
                        context.Result = new ObjectResult(ApiResponse<object>.Success("", result.Value));
                    //Logger.Trace($"执行{context.RouteData.Values["service"] ?? ""}.{context.RouteData.Values["moduleAction"] ?? ""} - " +
                    //    $"输出结果：{JsonHelper.TransferObjectJsonSerialize((context.Result as ObjectResult).Value, defaultValueIgnore: false)}");
                }
                else if (context.Result is EmptyResult)
                {
                    context.Result = new JsonResult(ApiResponse<string>.Success("执行成功！"));
                }
            }
            base.OnActionExecuted(context);
        }
    }
}